package com.tim.servlet;

import com.tim.pojo.DataResult;
import com.tim.pojo.User;
import com.tim.service.Impl.UserServiceImpl;
import com.tim.service.UserService;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 作者：Tim
 * 时间：2021/4/25 14:26
 */
@WebServlet("/user/*")
public class UserServlet extends BaseServlet{
    /**
     * 登录
     */
    //http://localhost:8080/user?method=login&username=admin&password=123&code=null
    public DataResult login(HttpServletRequest request, HttpServletResponse response){
        //1、获取请求参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String code = request.getParameter("code");
        String rememberme = request.getParameter("rememberMe"); //   选中返回on  未选中返回null

        //2、调用Service层登录方法
        UserService userService = new UserServiceImpl();
        User user = new User(username,password);
        boolean flag = userService.selectUserByname(user);
        DataResult dataResult;
        if(flag){
            HttpSession session = request.getSession();
            String text = (String)session.getAttribute("text");
            if(code!=null&&code.equalsIgnoreCase(text)){
                dataResult = new DataResult(0,"登录成功",user);
                //登陆成功将USer对象存入到session中
                ////b、登录成功之后，将用户名和密码保存 到cookie并添加到浏览器上
                //用户名:密码
//                if(rememberme=="on"){
                    Cookie cookie = new Cookie("userinfo",username+":"+password);
                    cookie.setPath("/");
                    cookie.setMaxAge(60*60*12);//存半天
                    response.addCookie(cookie);
//                }
                session.setAttribute("loginUser",user);
            }else{
                dataResult= new DataResult(40000,"验证码不正确");
            }
        }else{
            dataResult= new DataResult(40000,"账户密码不正确");
        }
        //当用户名密码或者是验证码输入错误，都从session中移除验证码信息
        HttpSession session = request.getSession();
        session.removeAttribute("text");
        return dataResult;
    }
}
